const { pool } = require('../config/db');

/**
 * 获取当前用户的家庭信息
 */
async function getUserFamily(req, res) {
  try {
    const userId = req.user.id;
    
    // 查询用户所属的家庭
    const [memberResults] = await pool.query(`
      SELECT f.*, fm.role 
      FROM families f
      JOIN family_members fm ON f.id = fm.family_id
      WHERE fm.user_id = ?
    `, [userId]);
    
    if (memberResults.length === 0) {
      return res.json({
        success: true,
        data: null,
        message: '用户尚未加入任何家庭'
      });
    }
    
    // 获取家庭成员信息
    const familyId = memberResults[0].id;
    const [members] = await pool.query(`
      SELECT u.id, u.username, u.email, u.phone, fm.role
      FROM users u
      JOIN family_members fm ON u.id = fm.user_id
      WHERE fm.family_id = ?
      ORDER BY fm.role = 'admin' DESC, u.username ASC
    `, [familyId]);
    
    // 获取家庭共享设备
    const [devices] = await pool.query(`
      SELECT d.id, d.name, d.type, ds.is_shared
      FROM devices d
      LEFT JOIN device_sharing ds ON d.id = ds.device_id AND ds.family_id = ?
      WHERE d.user_id = ? OR ds.family_id = ?
    `, [familyId, userId, familyId]);
    
    const family = {
      ...memberResults[0],
      members: members.map(member => ({
        id: member.id,
        name: member.username,
        email: member.email,
        phone: member.phone,
        role: member.role === 'admin' ? '管理员' : '成员',
        avatar: '' // 暂时没有头像字段
      })),
      devices: devices.map(device => ({
        id: device.id,
        name: device.name,
        type: device.type,
        isShared: device.is_shared === 1
      })),
      membersCount: members.length
    };
    
    res.json({
      success: true,
      data: family
    });
  } catch (error) {
    console.error('获取家庭信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取家庭信息失败',
      error: error.message
    });
  }
}

/**
 * 创建新家庭
 */
async function createFamily(req, res) {
  try {
    const userId = req.user.id;
    const { name, address, description } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '家庭名称是必需的'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 创建家庭
      const [result] = await connection.query(
        'INSERT INTO families (name, address, description) VALUES (?, ?, ?)',
        [name, address || null, description || null]
      );
      
      const familyId = result.insertId;
      
      // 添加当前用户为管理员
      await connection.query(
        'INSERT INTO family_members (family_id, user_id, role) VALUES (?, ?, ?)',
        [familyId, userId, 'admin']
      );
      
      // 更新用户默认家庭
      await connection.query(
        'UPDATE users SET default_family_id = ? WHERE id = ?',
        [familyId, userId]
      );
      
      await connection.commit();
      
      res.status(201).json({
        success: true,
        message: '家庭创建成功',
        data: {
          id: familyId,
          name,
          address,
          description
        }
      });
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('创建家庭失败:', error);
    res.status(500).json({
      success: false,
      message: '创建家庭失败',
      error: error.message
    });
  }
}

/**
 * 更新家庭信息
 */
async function updateFamily(req, res) {
  try {
    const userId = req.user.id;
    const familyId = req.params.familyId;
    const { name, address, description } = req.body;
    
    // 验证用户是否为家庭管理员
    const [adminCheck] = await pool.query(
      'SELECT * FROM family_members WHERE family_id = ? AND user_id = ? AND role = ?',
      [familyId, userId, 'admin']
    );
    
    if (adminCheck.length === 0) {
      return res.status(403).json({
        success: false,
        message: '只有管理员才能更新家庭信息'
      });
    }
    
    // 构建更新字段
    const updateFields = {};
    if (name) updateFields.name = name;
    if (address !== undefined) updateFields.address = address;
    if (description !== undefined) updateFields.description = description;
    
    if (Object.keys(updateFields).length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有提供要更新的信息'
      });
    }
    
    // 更新家庭信息
    await pool.query('UPDATE families SET ? WHERE id = ?', [updateFields, familyId]);
    
    res.json({
      success: true,
      message: '家庭信息已更新',
      data: {
        id: parseInt(familyId),
        ...updateFields
      }
    });
  } catch (error) {
    console.error('更新家庭信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新家庭信息失败',
      error: error.message
    });
  }
}

/**
 * 添加家庭成员
 */
async function addFamilyMember(req, res) {
  try {
    const userId = req.user.id;
    const familyId = req.params.familyId;
    const { memberEmail } = req.body;
    
    if (!memberEmail) {
      return res.status(400).json({
        success: false,
        message: '成员邮箱是必需的'
      });
    }
    
    // 验证用户是否为家庭管理员
    const [adminCheck] = await pool.query(
      'SELECT * FROM family_members WHERE family_id = ? AND user_id = ? AND role = ?',
      [familyId, userId, 'admin']
    );
    
    if (adminCheck.length === 0) {
      return res.status(403).json({
        success: false,
        message: '只有管理员才能添加家庭成员'
      });
    }
    
    // 查找要添加的用户
    const [users] = await pool.query('SELECT id FROM users WHERE email = ?', [memberEmail]);
    
    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该邮箱对应的用户'
      });
    }
    
    const newMemberId = users[0].id;
    
    // 检查用户是否已经是家庭成员
    const [existingMembers] = await pool.query(
      'SELECT * FROM family_members WHERE family_id = ? AND user_id = ?',
      [familyId, newMemberId]
    );
    
    if (existingMembers.length > 0) {
      return res.status(409).json({
        success: false,
        message: '该用户已经是家庭成员'
      });
    }
    
    // 添加新成员
    await pool.query(
      'INSERT INTO family_members (family_id, user_id, role) VALUES (?, ?, ?)',
      [familyId, newMemberId, 'member']
    );
    
    res.status(201).json({
      success: true,
      message: '家庭成员添加成功',
      data: {
        familyId: parseInt(familyId),
        userId: newMemberId,
        role: 'member'
      }
    });
  } catch (error) {
    console.error('添加家庭成员失败:', error);
    res.status(500).json({
      success: false,
      message: '添加家庭成员失败',
      error: error.message
    });
  }
}

/**
 * 更新家庭成员角色
 */
async function updateMemberRole(req, res) {
  try {
    const userId = req.user.id;
    const familyId = req.params.familyId;
    const memberId = req.params.memberId;
    const { role } = req.body;
    
    if (!role || !['admin', 'member'].includes(role)) {
      return res.status(400).json({
        success: false,
        message: '角色必须为 admin 或 member'
      });
    }
    
    // 验证用户是否为家庭管理员
    const [adminCheck] = await pool.query(
      'SELECT * FROM family_members WHERE family_id = ? AND user_id = ? AND role = ?',
      [familyId, userId, 'admin']
    );
    
    if (adminCheck.length === 0) {
      return res.status(403).json({
        success: false,
        message: '只有管理员才能更新成员角色'
      });
    }
    
    // 确保不是自己降级自己
    if (userId === parseInt(memberId) && role !== 'admin') {
      return res.status(400).json({
        success: false,
        message: '管理员不能降级自己的角色'
      });
    }
    
    // 更新成员角色
    await pool.query(
      'UPDATE family_members SET role = ? WHERE family_id = ? AND user_id = ?',
      [role, familyId, memberId]
    );
    
    res.json({
      success: true,
      message: '成员角色已更新',
      data: {
        familyId: parseInt(familyId),
        userId: parseInt(memberId),
        role
      }
    });
  } catch (error) {
    console.error('更新成员角色失败:', error);
    res.status(500).json({
      success: false,
      message: '更新成员角色失败',
      error: error.message
    });
  }
}

/**
 * 移除家庭成员
 */
async function removeFamilyMember(req, res) {
  try {
    const userId = req.user.id;
    const familyId = req.params.familyId;
    const memberId = req.params.memberId;
    
    // 验证用户是否为家庭管理员
    const [adminCheck] = await pool.query(
      'SELECT * FROM family_members WHERE family_id = ? AND user_id = ? AND role = ?',
      [familyId, userId, 'admin']
    );
    
    if (adminCheck.length === 0) {
      return res.status(403).json({
        success: false,
        message: '只有管理员才能移除家庭成员'
      });
    }
    
    // 确保不是自己移除自己
    if (userId === parseInt(memberId)) {
      return res.status(400).json({
        success: false,
        message: '管理员不能移除自己，请先转让管理员权限'
      });
    }
    
    // 移除成员
    const [result] = await pool.query(
      'DELETE FROM family_members WHERE family_id = ? AND user_id = ?',
      [familyId, memberId]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该家庭成员'
      });
    }
    
    res.json({
      success: true,
      message: '家庭成员已移除',
      data: {
        familyId: parseInt(familyId),
        userId: parseInt(memberId)
      }
    });
  } catch (error) {
    console.error('移除家庭成员失败:', error);
    res.status(500).json({
      success: false,
      message: '移除家庭成员失败',
      error: error.message
    });
  }
}

/**
 * 管理设备共享
 */
async function updateDeviceSharing(req, res) {
  try {
    const userId = req.user.id;
    const familyId = req.params.familyId;
    const deviceId = req.params.deviceId;
    const { isShared } = req.body;
    
    if (isShared === undefined) {
      return res.status(400).json({
        success: false,
        message: '共享状态是必需的'
      });
    }
    
    // 验证用户是否为设备所有者或家庭管理员
    const [deviceCheck] = await pool.query('SELECT user_id FROM devices WHERE id = ?', [deviceId]);
    
    if (deviceCheck.length === 0) {
      return res.status(404).json({
        success: false,
        message: '设备不存在'
      });
    }
    
    const deviceOwnerId = deviceCheck[0].user_id;
    
    // 验证用户是否为设备所有者或家庭管理员
    if (deviceOwnerId !== userId) {
      const [adminCheck] = await pool.query(
        'SELECT * FROM family_members WHERE family_id = ? AND user_id = ? AND role = ?',
        [familyId, userId, 'admin']
      );
      
      if (adminCheck.length === 0) {
        return res.status(403).json({
          success: false,
          message: '只有设备所有者或家庭管理员才能管理设备共享'
        });
      }
    }
    
    // 检查设备共享记录是否存在
    const [sharingCheck] = await pool.query(
      'SELECT * FROM device_sharing WHERE device_id = ? AND family_id = ?',
      [deviceId, familyId]
    );
    
    if (sharingCheck.length === 0) {
      // 创建新的共享记录
      await pool.query(
        'INSERT INTO device_sharing (device_id, family_id, shared_by, is_shared) VALUES (?, ?, ?, ?)',
        [deviceId, familyId, userId, isShared]
      );
    } else {
      // 更新现有共享记录
      await pool.query(
        'UPDATE device_sharing SET is_shared = ? WHERE device_id = ? AND family_id = ?',
        [isShared, deviceId, familyId]
      );
    }
    
    res.json({
      success: true,
      message: isShared ? '设备已共享' : '设备共享已取消',
      data: {
        deviceId: parseInt(deviceId),
        familyId: parseInt(familyId),
        isShared
      }
    });
  } catch (error) {
    console.error('更新设备共享状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新设备共享状态失败',
      error: error.message
    });
  }
}

/**
 * 获取用户可以访问的共享设备
 */
async function getUserSharedDevices(req, res) {
  try {
    const userId = req.user.id;
    const { type } = req.query; // 可选参数，用于筛选特定类型的设备
    
    // 查询用户所属的家庭
    const [families] = await pool.query(`
      SELECT f.id 
      FROM families f
      JOIN family_members fm ON f.id = fm.family_id
      WHERE fm.user_id = ?
    `, [userId]);
    
    if (families.length === 0) {
      return res.json({
        success: true,
        data: [],
        message: '用户尚未加入任何家庭'
      });
    }

    // 获取所有家庭ID
    const familyIds = families.map(f => f.id);
    
    // 构建查询语句
    let query = `
      SELECT d.id, d.name, d.type, d.device_id, d.user_id, d.room, d.connection_status, d.status, ds.is_shared, 
             u.username as owner_name
      FROM devices d
      JOIN device_sharing ds ON d.id = ds.device_id
      LEFT JOIN users u ON d.user_id = u.id
      WHERE ds.family_id IN (?) 
        AND ds.is_shared = 1
        AND d.user_id != ?
    `;
    
    const queryParams = [familyIds, userId];
    
    // 如果指定了设备类型，添加类型筛选条件
    if (type) {
      query += ` AND d.type = ?`;
      queryParams.push(type);
    }
    
    // 执行查询
    const [devices] = await pool.query(query, queryParams);
    
    res.json({
      success: true,
      data: devices
    });
  } catch (error) {
    console.error('获取共享设备失败:', error);
    res.status(500).json({
      success: false,
      message: '获取共享设备失败',
      error: error.message
    });
  }
}

module.exports = {
  getUserFamily,
  createFamily,
  updateFamily,
  addFamilyMember,
  updateMemberRole,
  removeFamilyMember,
  updateDeviceSharing,
  getUserSharedDevices
}; 